#include"tcpClient.h"
#include"ipAddressPort.h"
#include"logger.h"
#include"msg.h"
#include<cstring>

#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<string.h>
#include<fcntl.h>

TcpClient::TcpClient(const IpAddressPort  ipAddressPort)
{
   sfd_ = socket(AF_INET,SOCK_STREAM,0);
   if(-1 == sfd_)
   {
     LOG_FATAL << strerror(errno);
   }

   struct sockaddr_in ser;
   ser.sin_family = AF_INET;
   ser.sin_port = htons(ipAddressPort.GetPort());
   ser.sin_addr.s_addr = inet_addr(ipAddressPort.GetIpAddress().c_str());
   if(-1 == connect( sfd_,(struct sockaddr *)&ser,sizeof(ser)))
   {
     LOG_FATAL << strerror(errno);
   }
   LOG_INFO << "Server connect sucess";
}
TcpClient:: ~TcpClient()
{
   if(-1 == close( sfd_)){
      LOG_FATAL << strerror(errno);
   }
   LOG_INFO << "Client disconnect";
}
int TcpClient:: SendMsg(const std::string msg)
{
  int  numberOfSendByte = send( sfd_,msg.c_str(),strlen(msg.c_str()),0);
  if(-1 == numberOfSendByte)
  {
    LOG_ERROR << strerror(errno);
  }
  return numberOfSendByte;
} 
Msg TcpClient:: RecvMsg()
{
    char buff[LAGE_BUF_LEN] ={0};
    int  m_numberOfRecvBytes = recv( sfd_,buff,LAGE_BUF_LEN,0);
    if(  m_numberOfRecvBytes < 0 && (errno !=EAGAIN &&  errno != EWOULDBLOCK))
    {
        LOG_ERROR << strerror(errno);
    }
    return Msg{buff,m_numberOfRecvBytes};
}
int TcpClient::GetSfd()const
{
    return sfd_;
}
   
